import axios from 'axios';
import qs from 'qs';

let baseUrlNow;

if (process.env.NODE_ENV == 'development') {
    baseUrlNow = 'http://39.107.67.208:8888';
} else {
    baseUrlNow = `${location.origin}`;
}

/**
 * 自定义Axios实例
 */
const AJAX = axios.create({
    baseURL: baseUrlNow,
    timeout: 30000, //接口延时
    withCredentials: true //跨域
});

axios.interceptors.request.use(
    config => {
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response.data;
        } else {
            Promise.reject();
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

// 定义对外Get、Post、File请求
export default {
    get(url, param = {}, headers = {}) {
        return AJAX.get(url, {
            params: param,
            headers
        })
    },
    post(url, param = null, headers = {}) {
        param = qs.stringify(param)
        return AJAX.post(url, param, {
            headers
        })
        // application/x-www-form-urlencoded  默认post
    },
    // 针对于后台直接传参格式封装 例如 /{id}
    postParmas(url, paramlink = null, param = null, headers = {}) {
        return AJAX.post(url + '/' + paramlink, param, {
            headers: Object.assign({
                'Content-Type': 'application/json'
            }, headers)
        })
    },
    postJson(url, param = null, headers = {}) {
        return AJAX.post(url, param, {
            headers: Object.assign({
                'Content-Type': 'application/json'
            }, headers)
        })
        // Content-Type: application/json  json
    },
    put(url, param = null, headers = {}) {
        return AJAX.put(url, param, {
            headers
        })
    },
    file(url, param = null, headers = {}) {
        return AJAX.post(url, param, {
            headers: Object.assign({
                'Content-Type': 'multipart/form-data'
            }, headers)
        })
        // Content-Type: multipart/form-data
    },
    delete(url, param = null, headers = {}) {
        return AJAX.delete(url, {
            param,
            headers: Object.assign({
                'Content-Type': 'multipart/form-data'
            }, headers)
        })
    }
}
